package com.xq.shop.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.xq.shop.dao.IBaseDAO;
import com.xq.shop.util.HibernateUtil;
import com.xq.shop.vo.SearchObject;

@SuppressWarnings("unchecked")
public class BaseDAO<T> implements IBaseDAO<T> {

	//用于返回对象和获取范型class
	private Class<T> entityClass;
	private String entityName;
	
	public BaseDAO() {
		
		Type genType = getClass().getGenericSuperclass();  
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();  
        entityClass = (Class) params[0];  
        entityName = entityClass.getName();
	}
	
	@Override
	public void delete(List<Long> ids) {
		
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("ids", ids);
		HibernateUtil.execute("delete " + entityName + " where id in (:ids)", param);
	}

	@Override
	public T get(long id) {
		return (T)HibernateUtil.getTemplate().get(entityClass, id);
	}

	@Override
	public List<T> get(Long[] ids) {
		
		if(ids == null || ids.length <1) return new ArrayList<T>();
		
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("ids", ids);
		return (List<T>) HibernateUtil.executeFind(" from " + entityName +" where id in (:ids)", param);
	}

	@Override
	public List<T> get(SearchObject search) {
		return HibernateUtil.getPageObject(entityClass, search);
	}

	@Override
	public List<T> getAll() {
		return HibernateUtil.getTemplate().find(" from " + entityName);
	}

	@Override
	public long getCount(SearchObject search) {
		return HibernateUtil.getCount(entityClass, search);
	}

	@Override
	public void save(T obj) {
		HibernateUtil.getTemplate().save(obj);
	}
	
	@Override
	public void save(List<T> list) {
		
		if(list != null && list.size() > 0){
			
			for(T t : list){
				HibernateUtil.getTemplate().save(t);
			}
		}
	}

	@Override
	public void saveOrUpdate(T obj) {
		HibernateUtil.getTemplate().saveOrUpdate(obj);
	}
	
	@Override
	public void saveOrUpdateAll(List<T> list) {
		HibernateUtil.getTemplate().saveOrUpdateAll(list);
	}

	@Override
	public void update(T obj) {
		HibernateUtil.getTemplate().update(obj);
	}
	
	@Override
	public void update(List<T> list) {
		
		if(list != null && list.size() > 0){
			
			for(T t : list){
				HibernateUtil.getTemplate().update(t);
			}
		}
	}
}
